package cn.stylefeng.guns.modular.items.controller;

import cn.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import cn.stylefeng.guns.core.common.constant.factory.PageFactory;
import cn.stylefeng.guns.core.common.page.PageInfoBT;
import cn.stylefeng.guns.core.shiro.ShiroKit;
import cn.stylefeng.guns.core.shiro.ShiroUser;
import cn.stylefeng.guns.modular.account.service.IAccountService;
import cn.stylefeng.guns.modular.classification.service.IClassificationService;
import cn.stylefeng.guns.modular.family.service.IFamilyService;
import cn.stylefeng.guns.modular.familynum.service.IFamilynumService;
import cn.stylefeng.guns.modular.system.model.*;
import cn.stylefeng.guns.modular.system.service.IUserService;
import cn.stylefeng.guns.modular.system.warpper.AccountWarpper;
import cn.stylefeng.guns.modular.system.warpper.ItemsWarpper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.beans.factory.annotation.Autowired;
import cn.stylefeng.guns.core.log.LogObjectHolder;
import org.springframework.web.bind.annotation.RequestParam;
import cn.stylefeng.guns.modular.items.service.IItemsService;

import java.math.BigDecimal;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 账目表控制器
 *
 * @author fengshuonan
 * @Date 2021-04-11 15:59:10
 */
@Controller
@RequestMapping("/items")
public class ItemsController extends BaseController {

    private String PREFIX = "/items/items/";

    private String shouru = "srlx";

    private String zhichu="zclx";


    @Autowired
    private IItemsService itemsService;

    @Autowired
    private IAccountService accountService;

    @Autowired
    private IClassificationService classificationService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IFamilyService familyService;

    @Autowired
    private IFamilynumService familynumService;

    /**
     * 跳转到账目表首页
     */
    @RequestMapping("")
    public String index(Model model) {

        Integer userid=ShiroKit.getUser().getId();
        EntityWrapper<Account> accountEntityWrapper=new EntityWrapper<>();
        accountEntityWrapper.eq("userid",userid);
        List<Account> accountList=accountService.selectList(accountEntityWrapper);//本人的所有账户
        model.addAttribute("accountList",accountList);
        return PREFIX + "items.html";
    }

    /**
     * 跳转到添加账目表
     */
    @RequestMapping("/items_add")
    public String itemsAdd(Model model) {

        Integer userid= ShiroKit.getUser().getId();//当前用户的id

        EntityWrapper<Account> accountEntityWrapper=new EntityWrapper<>();
        accountEntityWrapper.eq("userid",userid);

        List<Account> accounts=accountService.selectList(accountEntityWrapper);
        model.addAttribute("accounts",accounts);

        return PREFIX + "items_add.html";
    }

    /**
     * 跳转到修改账目表
     */
    @RequestMapping("/items_update/{itemsId}")
    public String itemsUpdate(@PathVariable Integer itemsId, Model model) {
        //向前台传参
//        Integer userid= ShiroKit.getUser().getId();//当前用户的id
        Integer accountid=itemsService.selectById(itemsId).getAccountid();
        Integer userid=accountService.selectById(accountid).getUserid();

        EntityWrapper<Account> accountEntityWrapper=new EntityWrapper<>();
        accountEntityWrapper.eq("userid",userid);
        List<Account> accounts=accountService.selectList(accountEntityWrapper);
        model.addAttribute("accounts",accounts);

        //向前台传参
//        EntityWrapper<Classification> classificationEntityWrapper=new EntityWrapper<>();
//        classificationEntityWrapper.eq("pcode","zclx").or().eq("pcode","srlx");
//        List<Classification> classifications=classificationService.selectList(classificationEntityWrapper);
//        model.addAttribute("classifications",classifications);



        Items items = itemsService.selectById(itemsId);
        model.addAttribute("item",items);
        LogObjectHolder.me().set(items);

        return PREFIX + "items_edit.html";
    }

    /**
     * 获取账目表列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition,String condition2,String condition3,String condition4) {

//        return itemsService.selectList(null);
        Page<Map<String,Object>> page=new PageFactory<Map<String,Object>>().defaultPage();
        EntityWrapper<Items> itemsEntityWrapper=new EntityWrapper<>();
        itemsEntityWrapper.orderBy("id",false);

        Integer userid=ShiroKit.getUser().getId(); //用户id
        String roleid=userService.selectById(userid).getRoleid();//当前用户的角色id

//        if(roleid.equals("1")){ //超级管理员
//
//        }
//        else{
//            Integer familyid=userService.selectById(userid).getVersion();//当前用户的家庭id
//            Integer familyheadid=familyService.selectById(familyid).getCreateid();//户主的id
//            if(roleid.equals("5")){ //户主
//                EntityWrapper<Familynum> familynumEntityWrapper=new EntityWrapper<>();
//                familynumEntityWrapper.eq("familyid",familyid);
//                List<Familynum> familynumList=familynumService.selectList(familynumEntityWrapper); //筛选出同一个家庭的成员列表
//
//                List<Integer> useridlist=new LinkedList<>();  //用户userid
//                for(int i=0;i<familynumList.size();i++){
//                    Familynum f=familynumList.get(i);
//                    useridlist.add(f.getFamilyuserid());
//                }
//
//                EntityWrapper<Account> accountEntityWrapper=new EntityWrapper<>();
//                accountEntityWrapper.in("userid",useridlist);
//                List<Account> accountList=accountService.selectList(accountEntityWrapper);
//
//                List<Integer> accountidlist=new LinkedList<>();//家庭中所有成员的账户id
//                for(int i=0;i<accountList.size();i++){
//                    Account account=accountList.get(i);
//                    accountidlist.add(account.getId());
//                }
//
//                itemsEntityWrapper.in("accountid",accountidlist);
//            }
//            else{ //普通家庭成员
//                EntityWrapper<Account> accountEntityWrapper=new EntityWrapper<>();
//                accountEntityWrapper.eq("userid",userid);
//                List<Account> accountList=accountService.selectList(accountEntityWrapper);//本人的所有账户
//
//                List<Integer> accountidlist=new LinkedList<>();//本人的账户id
//                for(int i=0;i<accountList.size();i++){
//                    Account account=accountList.get(i);
//                    accountidlist.add(account.getId());
//                }
//                itemsEntityWrapper.in("accountid",accountidlist);
//            }
//        }

        EntityWrapper<Account> accountEntityWrapper=new EntityWrapper<>();
        accountEntityWrapper.eq("userid",userid);
        List<Account> accountList=accountService.selectList(accountEntityWrapper);//本人的所有账户


        List<Integer> accountidlist=new LinkedList<>();//本人的账户id
        for(int i=0;i<accountList.size();i++){
            Account account=accountList.get(i);
            accountidlist.add(account.getId());
        }




        if(accountidlist.size()==0){
            itemsEntityWrapper.eq("accountid",-1);
        }
        else{
            itemsEntityWrapper.in("accountid",accountidlist);
        }



        itemsEntityWrapper.like("accountid",condition);
        System.out.println("conditon"+condition+"*condition2"+condition2+"*condition3"+condition3+"***");
        if(condition3==""){


            if(condition2==""){

                itemsEntityWrapper.like("paykind",condition2);
            }
            else if(condition2.equals("zclx")){

                itemsEntityWrapper.like("paykind","zc");
            }
            else if(condition2.equals("srlx")){

                itemsEntityWrapper.like("paykind","sr");
            }

        }
        else{
            itemsEntityWrapper.like("paykind",condition3);
        }
        itemsEntityWrapper.like("paytime",condition4);



        Page<Map<String,Object>> mapPage=itemsService.selectMapsPage(page,itemsEntityWrapper);
        page=new ItemsWarpper(mapPage).wrap();
        return new PageInfoBT<>(page);
    }

    /**
     * 新增账目表
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(Items items) {

        //对应的账户金额减少
        Integer accountid=items.getAccountid();
        Account account=accountService.selectById(accountid);

        BigDecimal accountbalance=account.getAccountbalance();  //账户余额
        BigDecimal itemsbalance=items.getPay();  //账单金额

        String paykind=items.getPaykind(); //详细收支类型
        String pcode=ConstantFactory.me().getFatherCode(paykind);//收支类型


        if(pcode.equals(zhichu)) //支出 减法
        {
            account.setAccountbalance(accountbalance.subtract(itemsbalance));
        }
        else if(pcode.equals(shouru)){  //收入 加法
            account.setAccountbalance(accountbalance.add(itemsbalance));
        }

        accountService.updateById(account);

        items.setCreatetime(new Date());//设置创建时间
        items.setSpare1(paykind); //设置上一次的详细收支类型
        items.setSpare2(items.getAccountid().toString());//设置钱的来源账户id
        items.setSpare3(items.getPay().toString());//设置上一次的金额

        itemsService.insert(items);
        return SUCCESS_TIP;
    }

    /**
     * 删除账目表
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer itemsId) {
        //得到账户的id和收支类型
        Items items=itemsService.selectById(itemsId);
        BigDecimal balance=items.getPay();//账目金额
        Integer accountid=items.getAccountid(); //账户id

        Account account=accountService.selectById(accountid);
        account.setAccountbalance(account.getAccountbalance().add(balance));
        accountService.updateById(account);



        itemsService.deleteById(itemsId);
        return SUCCESS_TIP;
    }

    /**
     * 修改账目表
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(Items items) {
        //设置跟新时间和更新人
        items.setUpdatetime(new Date());
        Integer userid=ShiroKit.getUser().getId();
        items.setUpdateid(userid);

        System.out.println("**************"+items.getPayplace());

        //之前的账户和账户余额同步更新

        Integer lastAccountId=Integer.valueOf(items.getSpare2().toString()); //之前的账户id
        Account lastAccount=accountService.selectById(lastAccountId);//之前的账户
        BigDecimal lastbalance=lastAccount.getAccountbalance();
        String lastPcode= ConstantFactory.me().getFatherCode(items.getSpare1()); //之前的收支类型
//        BigDecimal lastPay=BigDecimal.valueOf(Integer.valueOf(items.getSpare3())); //之前的金额
        BigDecimal lastPay = new BigDecimal(items.getSpare3());

        if(lastPcode.equals(zhichu)){ //上一次是支出
            lastAccount.setAccountbalance(lastbalance.add(lastPay));
        }
        else if(lastPcode.equals(shouru)){ //上一次是收入
            lastAccount.setAccountbalance(lastbalance.subtract(lastPay));
        }



        //现在的账户和余额同步更新
        Account account=accountService.selectById(items.getAccountid());//现在的账户
        BigDecimal balance=account.getAccountbalance();
        String  pcode=ConstantFactory.me().getFatherCode(items.getPaykind());//现在的收支类型
        BigDecimal pay=account.getAccountbalance();

        if(pcode.equals(zhichu)){ //这一次是支出
            account.setAccountbalance(balance.subtract(items.getPay()));
        }
        else if(pcode.equals(shouru)){ //这一次是收入
            account.setAccountbalance(balance.add(items.getPay()));
        }

        //更新之前和现在的账户
        accountService.updateById(lastAccount);
        accountService.updateById(account);

        System.out.println("--------"+items.getPayplace());

        itemsService.updateById(items);

        return SUCCESS_TIP;
    }

    /**
     * 账目表详情
     */
    @RequestMapping(value = "/detail/{itemsId}")
    @ResponseBody
    public Object detail(@PathVariable("itemsId") Integer itemsId) {

        return itemsService.selectById(itemsId);
    }


    @RequestMapping(value = "/getMessage")
    @ResponseBody
    public List<Store> getMessage() {

        EntityWrapper<Classification> classificationEntityWrapper=new EntityWrapper<>();
        classificationEntityWrapper.eq("pcode","zclx").or().eq("pcode","srlx");
        List<Classification> classificationList=classificationService.selectList(classificationEntityWrapper);

        List<Store> storeList=new LinkedList<>();
        for(int i=0;i<classificationList.size();i++){
            Classification classification=classificationList.get(i);
            Store store=new Store();

            store.setV1(classification.getPcode());
            store.setV2(classification.getClasscode());
            store.setV3(classification.getName());

            storeList.add(store);
        }
        return storeList;

    }



}
